<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>专注计时器 - 微休息深绿色版</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
            background-color: #F1F8E9;
            color: #33691E;
        }
        h1 {
            color: #2E7D32;
            text-align: center;
            margin-bottom: 20px;
        }
        .timer-container {
            background-color: #DCEDC8;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border: 1px solid #C5E1A5;
        }
        .timer-display {
            font-size: 48px;
            text-align: center;
            margin: 20px 0;
            font-weight: bold;
            color: #1B5E20;
        }
        .controls {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            background-color: #689F38;
            color: white;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #558B2F;
        }
        button:disabled {
            background-color: #95a5a6;
            cursor: not-allowed;
        }
        .test-alert-btn {
            background-color: #7CB342;
        }
        .settings {
            background-color: #DCEDC8;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            border: 1px solid #C5E1A5;
        }
        .setting-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            align-items: center;
        }
        input {
            padding: 8px;
            border: 1px solid #C5E1A5;
            border-radius: 4px;
            width: 80px;
            background-color: #F1F8E9;
        }
        .status {
            text-align: center;
            margin-top: 20px;
            font-weight: bold;
            color: #D84315;
        }
        .mode-indicator {
            text-align: center;
            font-size: 18px;
            margin-bottom: 10px;
            font-weight: bold;
        }
        .focus { color: #2E7D32; }
        .break { color: #EF6C00; }
        .micro-break { color: #F9A825; }
        .screen-wake-status {
            text-align: center;
            margin-top: 10px;
            font-size: 14px;
            color: #7f8c8d;
        }
        
        /* 微休息深绿色界面 */
        .visual-alert {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: #1B5E20;
            display: none;
            z-index: 1000;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }
        .alert-message {
            font-size: 2rem;
            color: #E8F5E9;
            text-align: center;
            margin-bottom: 20px;
        }
        .micro-break-countdown {
            font-size: 3rem;
            font-weight: bold;
            color: #FFFFFF;
            margin-bottom: 20px;
        }
        .close-alert-btn {
            background-color: #81C784;
            padding: 12px 24px;
            font-size: 1.2rem;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .close-alert-btn:hover {
            background-color: #66BB6A;
        }
        .permission-hint {
            background-color: #FFF9C4;
            padding: 10px;
            border-radius: 5px;
            margin-top: 10px;
            font-size: 14px;
            display: none;
            color: #5D4037;
            border: 1px solid #FFEE58;
        }
    </style>
</head>
<body>
    <h1>专注计时器 - 微休息深绿色版</h1>
    
    <div class="timer-container">
        <div class="mode-indicator">
            <span id="mode-text">准备开始</span>
        </div>
        <div class="timer-display" id="timer">90:00</div>
        <div class="controls">
            <button id="start-btn">开始</button>
            <button id="pause-btn" disabled>暂停</button>
            <button id="reset-btn">重置</button>
            <button id="test-alert-btn" class="test-alert-btn">测试提醒</button>
        </div>
        <div class="status" id="status"></div>
        <div class="screen-wake-status" id="wake-lock-status">屏幕常亮: 未激活</div>
        <div class="permission-hint" id="permission-hint">
            如果提醒不工作，请点击"测试提醒"按钮并允许通知和声音权限
        </div>
    </div>
    
    <div class="settings">
        <h2>设置</h2>
        <div class="setting-row">
            <label for="focus-time">专注时间 (分钟):</label>
            <input type="number" id="focus-time" min="1" value="90">
        </div>
        <div class="setting-row">
            <label for="min-random">提示音最小间隔 (分钟):</label>
            <input type="number" id="min-random" min="1" value="2">
        </div>
        <div class="setting-row">
            <label for="max-random">提示音最大间隔 (分钟):</label>
            <input type="number" id="max-random" min="1" value="5">
        </div>
        <div class="setting-row">
            <label for="micro-break">微休息时间 (秒):</label>
            <input type="number" id="micro-break" min="1" value="10">
        </div>
        <div class="setting-row">
            <label for="break-time">休息时间 (分钟):</label>
            <input type="number" id="break-time" min="1" value="20">
        </div>
    </div>

    <!-- 深绿色视觉提醒层 -->
    <div class="visual-alert" id="visual-alert">
        <div class="alert-message" id="alert-message">微休息时间到！</div>
        <div class="micro-break-countdown" id="micro-break-countdown">10秒</div>
        <button class="close-alert-btn" id="close-alert-btn">提前结束</button>
    </div>

    <!-- 音频元素 -->
    <audio id="alert-sound" preload="auto">
     <!-- 选项1：短促蜂鸣声（0.5秒） -->
    <source src="https://assets.mixkit.co/sfx/preview/mixkit-electronic-digital-clock-beep-989.mp3" type="audio/mpeg">
    
    <!-- 选项2：清脆提示音（1秒） -->
    <source src="https://assets.mixkit.co/sfx/preview/mixkit-software-interface-start-2574.mp3" type="audio/mpeg">
    </audio>

    <script>
        // 设备能力检测
        const supports = {
            vibration: 'vibrate' in navigator,
            wakeLock: 'wakeLock' in navigator,
            notifications: 'Notification' in window
        };
        
        // DOM元素
        const timerDisplay = document.getElementById('timer');
        const startBtn = document.getElementById('start-btn');
        const pauseBtn = document.getElementById('pause-btn');
        const resetBtn = document.getElementById('reset-btn');
        const testAlertBtn = document.getElementById('test-alert-btn');
        const statusText = document.getElementById('status');
        const modeText = document.getElementById('mode-text');
        const alertSound = document.getElementById('alert-sound');
        const wakeLockStatus = document.getElementById('wake-lock-status');
        const visualAlert = document.getElementById('visual-alert');
        const alertMessage = document.getElementById('alert-message');
        const microBreakCountdown = document.getElementById('micro-break-countdown');
        const closeAlertBtn = document.getElementById('close-alert-btn');
        const permissionHint = document.getElementById('permission-hint');
        
        // 设置输入
        const focusTimeInput = document.getElementById('focus-time');
        const minRandomInput = document.getElementById('min-random');
        const maxRandomInput = document.getElementById('max-random');
        const microBreakInput = document.getElementById('micro-break');
        const breakTimeInput = document.getElementById('break-time');
        
        // 计时器变量
        let timer;
        let totalSeconds = 90 * 60;
        let remainingSeconds = totalSeconds;
        let isRunning = false;
        let isFocusMode = true;
        let nextAlertTime = 0;
        let microBreakSeconds = 0;
        let wakeLock = null;
        let microBreakTimer = null;
        let microBreakCountdownValue = 10;
        let blinkInterval;

        // 初始化
        async function init() {
            updateDisplay();
            startBtn.addEventListener('click', startTimer);
            pauseBtn.addEventListener('click', pauseTimer);
            resetBtn.addEventListener('click', resetTimer);
            testAlertBtn.addEventListener('click', testAlert);
            closeAlertBtn.addEventListener('click', closeAlert);
            
            // 监听页面可见性变化
            document.addEventListener('visibilitychange', handleVisibilityChange);
            
            // 检查Wake Lock API支持
            if (supports.wakeLock) {
                wakeLockStatus.textContent = "屏幕常亮: 支持 (未激活)";
            } else {
                wakeLockStatus.textContent = "屏幕常亮: 您的浏览器不支持此功能";
            }
            
            // 预加载音频
            try {
                await alertSound.load();
            } catch (e) {
                console.log("音频预加载失败:", e);
            }
        }
        
        // 测试提醒
        async function testAlert() {
            await triggerAlert('测试提醒功能');
        }
        
        // 关闭提醒
        function closeAlert() {
            clearInterval(microBreakTimer);
            microBreakTimer = null;
            visualAlert.style.display = 'none';
            microBreakSeconds = 0;
            statusText.textContent = '';
            modeText.textContent = '专注模式';
            modeText.className = 'mode-indicator focus';
            stopTitleBlink();
        }
        
        // 处理页面可见性变化
        function handleVisibilityChange() {
            if (document.hidden) {
                console.log('页面在后台运行，计时器继续...');
            }
        }
        
        // 开始计时器
        async function startTimer() {
            if (isRunning) return;
            
            totalSeconds = parseInt(focusTimeInput.value) * 60;
            remainingSeconds = totalSeconds;
            isFocusMode = true;
            setNextAlertTime();
            
            isRunning = true;
            startBtn.disabled = true;
            pauseBtn.disabled = false;
            modeText.textContent = '专注模式';
            modeText.className = 'mode-indicator focus';
            statusText.textContent = '';
            permissionHint.style.display = 'none';
            
            await requestWakeLock();
            
            timer = setInterval(updateTimer, 1000);
        }
        
        // 暂停计时器
        async function pauseTimer() {
            clearInterval(timer);
            isRunning = false;
            startBtn.disabled = false;
            pauseBtn.disabled = true;
            modeText.textContent = '已暂停';
            modeText.className = 'mode-indicator';
            
            await releaseWakeLock();
        }
        
        // 重置计时器
        async function resetTimer() {
            clearInterval(timer);
            clearInterval(microBreakTimer);
            isRunning = false;
            remainingSeconds = parseInt(focusTimeInput.value) * 60;
            isFocusMode = true;
            startBtn.disabled = false;
            pauseBtn.disabled = true;
            modeText.textContent = '准备开始';
            modeText.className = 'mode-indicator';
            statusText.textContent = '';
            permissionHint.style.display = 'none';
            visualAlert.style.display = 'none';
            
            await releaseWakeLock();
            stopTitleBlink();
            
            updateDisplay();
        }
        
        // 更新计时器
        function updateTimer() {
            remainingSeconds--;
            
            // 检查是否该触发提醒
            if (isFocusMode) {
                const elapsed = totalSeconds - remainingSeconds;
                if (elapsed >= nextAlertTime) {
                    triggerMicroBreakAlert();
                    setNextAlertTime();
                }
                
                // 处理微休息
                if (microBreakSeconds > 0) {
                    microBreakSeconds--;
                    return; // 微休息时不减少主计时器
                }
            }
            
            // 检查是否时间到
            if (remainingSeconds <= 0) {
                if (isFocusMode) {
                    // 专注时间结束，开始休息
                    isFocusMode = false;
                    remainingSeconds = parseInt(breakTimeInput.value) * 60;
                    modeText.textContent = '休息时间';
                    modeText.className = 'mode-indicator break';
                    triggerAlert('专注时间结束，请休息！');
                } else {
                    // 休息时间结束，重置
                    resetTimer();
                    triggerAlert('休息时间结束，准备开始新一轮专注！');
                    return;
                }
            }
            
            updateDisplay();
        }
        
        // 触发微休息提醒
        async function triggerMicroBreakAlert() {
            microBreakSeconds = parseInt(microBreakInput.value);
            statusText.textContent = '微休息中...';
            modeText.textContent = '微休息';
            modeText.className = 'mode-indicator micro-break';
            alertMessage.textContent = '微休息时间到！';
            visualAlert.style.display = 'flex';
            startMicroBreakCountdown();
            await triggerAlert('微休息时间到！');
        }
        
        // 开始微休息倒计时
        function startMicroBreakCountdown() {
            clearInterval(microBreakTimer);
            microBreakCountdownValue = parseInt(microBreakInput.value) || 10;
            updateMicroBreakCountdown();
            
            microBreakTimer = setInterval(() => {
                microBreakCountdownValue--;
                updateMicroBreakCountdown();
                
                if (microBreakCountdownValue <= 0) {
                    closeAlert();
                }
            }, 1000);
        }
        
        // 更新微休息倒计时显示
        function updateMicroBreakCountdown() {
            microBreakCountdown.textContent = `${microBreakCountdownValue}秒`;
        }
        
        // 触发通用提醒
        async function triggerAlert(message) {
            // 播放声音
            let soundPlayed = false;
            try {
                alertSound.currentTime = 0;
                await alertSound.play();
                soundPlayed = true;
            } catch (e) {
                console.log("音频播放失败:", e);
            }
            
            // 设备振动
            let vibrationPlayed = false;
            if (supports.vibration) {
                try {
                    navigator.vibrate([200, 100, 400, 100, 200]);
                    vibrationPlayed = true;
                } catch (e) {
                    console.log("振动失败:", e);
                }
            }
            
            // 系统通知
            if (supports.notifications && Notification.permission === 'granted') {
                try {
                    new Notification('专注计时器提醒', { body: message });
                } catch (e) {
                    console.log("通知发送失败:", e);
                }
            }
            
            // 页面标题闪烁
            startTitleBlink(message);
            
            if (!soundPlayed || !vibrationPlayed) {
                permissionHint.style.display = 'block';
            }
        }
        
        // 页面标题闪烁
        function startTitleBlink(message) {
            stopTitleBlink();
            let counter = 0;
            const originalTitle = document.title;
            blinkInterval = setInterval(() => {
                document.title = (counter++ % 2 === 0) 
                    ? `⏰ ${message}` 
                    : originalTitle;
            }, 800);
        }
        
        function stopTitleBlink() {
            if (blinkInterval) {
                clearInterval(blinkInterval);
                blinkInterval = null;
                document.title = '专注计时器 - 微休息深绿色版';
            }
        }
        
        // 请求屏幕常亮
        async function requestWakeLock() {
            if (supports.wakeLock) {
                try {
                    wakeLock = await navigator.wakeLock.request('screen');
                    wakeLockStatus.textContent = "屏幕常亮: 已激活";
                    wakeLock.addEventListener('release', () => {
                        wakeLockStatus.textContent = "屏幕常亮: 已释放";
                    });
                } catch (err) {
                    wakeLockStatus.textContent = `屏幕常亮: 激活失败 (${err.message})`;
                }
            }
        }
        
        // 释放屏幕常亮
        async function releaseWakeLock() {
            if (wakeLock) {
                await wakeLock.release();
                wakeLock = null;
                wakeLockStatus.textContent = "屏幕常亮: 已释放";
            }
        }
        
        // 设置下一个提醒时间
        function setNextAlertTime() {
            const min = parseInt(minRandomInput.value) * 60;
            const max = parseInt(maxRandomInput.value) * 60;
            const elapsed = totalSeconds - remainingSeconds;
            nextAlertTime = elapsed + min + Math.floor(Math.random() * (max - min + 1));
        }
        
        // 更新显示
        function updateDisplay() {
            const minutes = Math.floor(remainingSeconds / 60);
            const seconds = remainingSeconds % 60;
            timerDisplay.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }
        
        // 启动应用
        init();
    </script>
</body>
</html>